package me.liuyu2783.dubbo.sample.dubbo;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;
import java.util.Random;

/**
 * me.liuyu2783.dubbo.sample.dubbo
 *
 * @author liuyu2783
 * @date 2020-3-3
 */
public class ProxyFactory {

    public static <T> T getProxy(Class interfaceClass){
        return (T)Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Invocation invocation = new Invocation();
                invocation.setInterfaceName(interfaceClass.getName());
                invocation.setMethodName(method.getName());
                invocation.setParamType(method.getParameterTypes());
                invocation.setParams(args);

                //loadbalance
                List<URL> urlList = RemoteRegister.getUrlList(interfaceClass.getName());
                Integer index = new Random(urlList.size()).nextInt();
                URL url = urlList.get(index);

//                Object result = new HttpClient().send(url.getHost(),url.getPort(), invocation);
//                Protocol protocol = new HttpProtocol();

                Protocol protocol = ProtocolFactory.getProtocal();
                Object result = protocol.send(url, invocation);
                return result;
            }
        });
    }
}
